package vn.mobiistar.videoapp.fragment;
import java.util.ArrayList;

import vn.mobiistar.videoapp.R;
import vn.mobiistar.videoapp.activity.MainActivity;
import vn.mobiistar.videoapp.loader.BaseLoader;
import vn.mobiistar.videoapp.loader.BaseResult;
import vn.mobiistar.videoapp.loader.VideoLoader;
import vn.mobiistar.videoapp.other.Define;
import vn.mobiistar.videoapp.other.Video;
import vn.mobiistar.videoapp.other.VideoPlayer;
import vn.mobiistar.videoapp.ui.BlockView;
import vn.mobiistar.videoapp.ui.Refreshable;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.github.pedrovgs.DraggablePanel;

public class IndexFragment extends BaseFragment  implements
LoaderCallbacks<BaseResult>, Refreshable {
	public ArrayList<ArrayList<Video>>   mDataList;
	public BaseLoader[] 				 mLoaderList;
	public boolean[]  					 mIsReachedBottom;
	public BlockView[] 				     mBlockList;
	public Context 					 	 mContext;
	public View 						 content;
	public static final int 			 DELAY_MILLIS = 10;
	public IndexFragment(Context context){
		mContext = context;
	}
	public IndexFragment(){
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		
		content = inflater.inflate(R.layout.fragment_index, null);
		mDataList = new ArrayList<ArrayList<Video>>();
		// 43 add fix: tranh truong hop loader có id lớn hơn chạy trước sẽ gây
		// lỗi nullpointed
		for (int i = 0; i < Define.MAXIMUM_BLOCK_QUAN_INDEX; i++) {
			mDataList.add(i, null);
		}
		mBlockList 			= new BlockView[Define.MAXIMUM_BLOCK_QUAN_INDEX];
		mLoaderList 		= new BaseLoader[Define.MAXIMUM_BLOCK_QUAN_INDEX];
		mIsReachedBottom 	= new boolean[Define.MAXIMUM_BLOCK_QUAN_INDEX];
		//draggablePanel 		= ((MainActivity)mContext).mDragableView;
		draggablePanel 		= (DraggablePanel) content.findViewById(R.id.fi_draggable_panel);
		mPlayer             = new VideoPlayer(getActivity(), this, draggablePanel);
		
		BaseLoader tmp 	= new VideoLoader(mContext);
		((VideoLoader) tmp) .setType(Define.BLOCK_TYPE_NEW);
		BaseLoader tmp2 = new VideoLoader(mContext);
		((VideoLoader) tmp2).setType(Define.BLOCK_TYPE_MOSTVIEW);
		mLoaderList[Define.BLOCK_TYPE_NEW - 1] 		= tmp;
		mLoaderList[Define.BLOCK_TYPE_MOSTVIEW - 1] = tmp2;
		_initView(content);
		return content;
	}
	private void _initView(View root) {
		// bo xu ly su kien khi click vao video tren list view
		ListView.OnItemClickListener loi = new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					onVideoClick(parent,  view,position,  id);
			}
		};
		LinearLayout ll_root = (LinearLayout) root.findViewById(R.id.fi_blockcontain);

		BlockView newVideo = new BlockView(mContext, null);
		newVideo.setTitle(R.string.blocktitle_new);
		newVideo.getLoadMore().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				VideoLoader loader = ((VideoLoader) IndexFragment.this.mLoaderList[Define.BLOCK_TYPE_NEW - 1]);
				if (loader != null
						&& !loader.isLoading()
						&& (!IndexFragment.this.mIsReachedBottom[Define.BLOCK_TYPE_NEW - 1])) {
					loader.nextPage();
					loader.forceLoad();
				}
				// fix bug
				if(mPlayer.getYoutubePlayer() != null) if( !mPlayer.isPlaying()) draggablePanel.setVisibility(View.GONE);
			}
		});
		newVideo.getList().setOnItemClickListener(loi);
		BlockView mostviewVideo = new BlockView(mContext, null);
		mostviewVideo.setTitle(R.string.blocktitle_mostview);
		mostviewVideo.getLoadMore().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				VideoLoader loader = ((VideoLoader) IndexFragment.this.mLoaderList[Define.BLOCK_TYPE_MOSTVIEW - 1]);
				if (loader != null
						&& !loader.isLoading()
						&& (!IndexFragment.this.mIsReachedBottom[Define.BLOCK_TYPE_MOSTVIEW - 1])) {
					loader.nextPage();
					loader.forceLoad();
				}
			}
		});
		mostviewVideo.getList().setOnItemClickListener(loi);
		
		// bo view vao mang de tien truy cap
		mBlockList[Define.BLOCK_TYPE_NEW - 1] = newVideo;
		mBlockList[Define.BLOCK_TYPE_MOSTVIEW - 1] = mostviewVideo;
		
		// them view vao root de hien thi
		ll_root.addView(mBlockList[Define.BLOCK_TYPE_NEW - 1]);
		ll_root.addView(mBlockList[Define.BLOCK_TYPE_MOSTVIEW - 1]);
		
		
		((MainActivity)getActivity()).currentFragment = this;
	}
	
	public void switchToNewVideoOnly(){
		mBlockList[Define.BLOCK_TYPE_MOSTVIEW - 1].setVisibility(View.GONE);
		mBlockList[Define.BLOCK_TYPE_MOSTVIEW - 1].switchToScrollMode();
		
	}
	
	public void switchToMostViewOnly(){
		mBlockList[Define.BLOCK_TYPE_NEW - 1].setVisibility(View.GONE);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		getLoaderManager().initLoader(Define.BLOCK_TYPE_NEW, null, this);
		getLoaderManager().initLoader(Define.BLOCK_TYPE_MOSTVIEW, null,this);
		// xu ly nut back
//		this.getView().setFocusableInTouchMode(true);
//		this.getView().setOnKeyListener( new OnKeyListener(){
//		    @Override
//		    public boolean onKey( View v, int keyCode, KeyEvent event ){
//		        if( keyCode == KeyEvent.KEYCODE_BACK ){
//		        	if(mPlayer!= null && mIsInitialVideoPlayer) 
//		        		if(mPlayer.getDraggablePanel()!=null)
//		        			if(mPlayer.getDraggablePanel().isMaximized()) 
//		        				mPlayer.getDraggablePanel().minimize();
//		            return true;
//		        }
//		        return false;
//		    }
//		} );
		
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public Loader<BaseResult> onCreateLoader(int id, Bundle arg1) {
		 mLoaderList[id-1].setProgressNotifiable( mBlockList[id-1].getLoadingView());
		return mLoaderList[id - 1];
	}

	@Override
	public void onLoadFinished(Loader<BaseResult> loader,
			final BaseResult result) {
		// TODO Auto-generated method stub
		final int id = loader.getId();
		((MainActivity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (((VideoLoader.Result) result).mVideo.size() > 0) {
					mDataList.add(id - 1, ((VideoLoader.Result) result).mVideo);
					mBlockList[id - 1].setData(mDataList.get(id - 1));
				} else{
					mIsReachedBottom[id - 1] = true;
					mBlockList[id - 1].setNoButtonLoadMore();
				}
			}
		});
	}

	@Override
	public void onLoaderReset(Loader<BaseResult> arg0) {
	}

	@Override
	public void refreshData() {
	}
}
